using System;
using Microsoft.SPOT;

namespace dotnetwarrior.NetMF.Diagnostics
{
  public class Stopwatch
  {
    private DateTime _start;
    private DateTime _end;
    private TimeSpan _elapsedTime = TimeSpan.Zero;

    public bool IsRunning { get; private set; }

    public TimeSpan Elapsed
    {
      get { return _elapsedTime + (_end - _start); }
    }

    public long ElapsedMilliseconds
    {
      get { return Elapsed.Ticks / TimeSpan.TicksPerMillisecond; }
    }

    public long ElapsedTicks
    {
      get { return Elapsed.Ticks; }
    }

    public long GetTimestamp()
    {
      return DateTime.Now.Ticks;
    }

    public void Start()
    {
      if (!IsRunning)
      {
        IsRunning = true;
        _start = DateTime.Now;        
      }
    }

    public void Stop()
    {
      if (IsRunning)
      {
        _end = DateTime.Now;
        _elapsedTime += _end - _start;
        IsRunning = false;
      }
    }

    public void Reset()
    {
      Stop();
      _elapsedTime = TimeSpan.Zero;
    }

    public void Restart()
    {
      Reset();
      Start();
    }

    public static Stopwatch StartNew()
    {
      Stopwatch sw = new Stopwatch();
      sw.Start();
      return sw;
    }
  }
}
